package com.luckdraw.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.nutz.http.Header;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.lang.Xmls;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class ClientSendHongBaoCustomSSL {
	
	private static Log log = Logs.getLog("ClientSendHongBaoCustomSSL");
	
	/**
	 * @param openid 用户openid
	 * @param momney 金额 单位：分
	 * @param mch_id 商户号
	 * @param wxappid  公众账号appid
	 */
	public static NutMap sxtd(String openid, int momney, String mch_id, String wxappid, String apiKey) throws Exception {
		NutMap result = new NutMap();
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		FileInputStream instream = new FileInputStream(new File(Constant.APICLIENT_CERT));
		try {
			keyStore.load(instream, mch_id.toCharArray());
		} finally {
			instream.close();
		}
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		CloseableHttpResponse response = null;
		String mch_billno = CreateOrderNum.create(mch_id);// 商户订单号
		try {
			HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");
			NutMap m = NutMap.NEW();
			String nonce_str = GetUUID.getUUID();// 32位随机字段
			m.put("nonce_str", nonce_str);
			m.put("mch_billno", mch_billno);
			m.put("mch_id", mch_id);
			m.put("wxappid", wxappid);
			String send_name = Constant.SEND_NAME;// 商户名称
			m.put("send_name", send_name);
			String re_openid = openid;// 用户openid op-SgtxWb5nCGtANlrQgVP2exD_U
			m.put("re_openid", re_openid);
			int total_amount = momney;// 付款金额 付款金额，单位分
			m.put("total_amount", String.valueOf(total_amount));
			int total_num = 1;// 红包发放总人数
			m.put("total_num", String.valueOf(total_num));
			String wishing = Constant.WISHING;// 红包祝福语
			m.put("wishing", wishing);
			String client_ip = Constant.CLIENT_IP;// Ip地址
			m.put("client_ip", client_ip);
			String act_name = Constant.ACT_NAME;// 活动名称
			m.put("act_name", act_name);
			String remark = Constant.REMARK;// 备注
			m.put("remark", remark);
			String sign = TenpayUtil.genPackageSign(TenpayUtil.toSortedMap(m), apiKey);// 签名
			m.put("sign", sign);
			// System.out.println(Json.toJson(m));
			String xml = Xmls.mapToXml(m);
			post.setEntity(new StringEntity(xml, "UTF-8"));
			response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
				String text;
				String res = "";
				while ((text = bufferedReader.readLine()) != null) {
					res += text;
				}
				log.info("ClientSendHongBaoCustomSSL|openid:" + openid + ",微信返回的数据:" + res);
				try {
					result = Xmls.xmlToMap(res);
				} catch (Exception e) {
					result.addv("return_code", "SUCCESS");
					result.addv("return_msg", "SUCCESS");
					result.addv("result_code", "FAIL");
					result.addv("err_code_des", "解析微信结果出错");
				}
			}
			EntityUtils.consume(entity);
		} catch (Exception e) {
			result.addv("return_code", "SUCCESS");
			result.addv("return_msg", "SUCCESS");
			result.addv("result_code", "FAIL");
			result.addv("err_code_des", "发送红包出错");
			log.info("ClientSendHongBaoCustomSSL|openid:" + openid + ",异常:" + e.getMessage());
			e.printStackTrace();
		} finally {
			if (null != response) {
				response.close();
			}
			httpclient.close();
		}
		result.addv("mch_billno", mch_billno);
		return result;
	}
    
    /**
	 * @param openid 用户openid
	 * @param momney 金额 单位：分
	 * @param mch_id 商户号
	 * @param wxappid  公众账号appid
	 */
    public static NutMap sxtd1(String openid, int momney,String mch_id,String wxappid,String apiKey)throws Exception {
    	NutMap respMap = null;
    	NutMap m = NutMap.NEW();
		String nonce_str=GetUUID.getUUID();//32位随机字段
		m.put("nonce_str",nonce_str);
		String mch_billno=CreateOrderNum.create(mch_id);//商户订单号
		m.put("mch_billno",mch_billno);
		m.put("mch_id",mch_id);
		m.put("wxappid",wxappid);
		String send_name=Constant.SEND_NAME;//商户名称
		m.put("send_name",send_name);
		String re_openid=openid;//用户openid   op-SgtxWb5nCGtANlrQgVP2exD_U
		m.put("re_openid",re_openid);
		int total_amount=momney;//付款金额 付款金额，单位分
		m.put("total_amount",String.valueOf(total_amount));
		int total_num=1;//红包发放总人数
		m.put("total_num",String.valueOf(total_num));
		String wishing=Constant.WISHING;//红包祝福语
		m.put("wishing",wishing);
		String client_ip=Constant.CLIENT_IP;//Ip地址
		m.put("client_ip",client_ip);
		String act_name=Constant.ACT_NAME;//活动名称
		m.put("act_name",act_name);
		String remark=Constant.REMARK;//备注
		m.put("remark",remark);
		System.out.println(apiKey);
		String sign=TenpayUtil.genPackageSign(TenpayUtil.toSortedMap(m),apiKey);//签名
		m.put("sign",sign);
		String xml=Xmls.mapToXml(m);
		Response response = Http.post3("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack", xml,Header.create().asFormContentType("application/xml"), 60000);
		if(response.isOK()){
			String respStr = response.getContent();
			System.out.println(respStr);
			try{
				respMap = Xmls.xmlToMap(respStr);
				log.info("ClientSendHongBaoCustomSSL|openid:"+openid+",微信返回的数据:"+respStr);
				respMap.addv("mch_billno",mch_billno);
			}catch(Exception e){
				respMap.addv("", "");
	        	log.info("ClientSendHongBaoCustomSSL|openid:"+openid+",异常:"+e.getMessage());
				e.printStackTrace();
			}
		}
		return respMap;
    }

}
